package com.smart.community.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志过滤器
 * 
 * @author Wu.Liang
 * @since 2024-01-15
 */
@Slf4j
@Component
public class LogFilter implements GlobalFilter, Ordered {
    
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String clientIp = getClientIp(request);
        String method = request.getMethod().name();
        String path = request.getURI().getPath();
        String startTime = LocalDateTime.now().format(FORMATTER);
        
        log.info("请求开始 - 时间: {}, IP: {}, 方法: {}, 路径: {}", 
                startTime, clientIp, method, path);
        
        return chain.filter(exchange)
                .doFinally(signalType -> {
                    String endTime = LocalDateTime.now().format(FORMATTER);
                    log.info("请求结束 - 时间: {}, IP: {}, 方法: {}, 路径: {}, 状态: {}", 
                            endTime, clientIp, method, path, 
                            exchange.getResponse().getStatusCode());
                });
    }
    
    /**
     * 获取客户端IP
     */
    private String getClientIp(ServerHttpRequest request) {
        String xRealIp = request.getHeaders().getFirst("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        
        String xForwardedFor = request.getHeaders().getFirst("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        return request.getRemoteAddress() != null ? 
               request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
    }
    
    @Override
    public int getOrder() {
        return -200; // 最低优先级，最后执行
    }
} 